package org.babygo.connect.client;

import java.nio.channels.Channel;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import org.babygo.connect.handler.client.file.ClientSendFileOutHandler;
import org.babygo.connect.handler.client.msg.ClientClosedInHandler;
import org.babygo.connect.handler.client.msg.ClientRequestInHandler;
import org.babygo.connect.handler.code.DecodeInHandler;
import org.babygo.connect.handler.code.EncodeOutHandler;
import org.babygo.connect.protocol.GetAndSendFileRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClient {
	private Logger log = LoggerFactory.getLogger(NettyClient.class);

	private EventLoopGroup workerGroup;
	private ChannelFuture channelFuture;

	public boolean connectClient(String ip, int port){
		Bootstrap bootstrap = new Bootstrap();
		workerGroup  = new NioEventLoopGroup();
		bootstrap.group(workerGroup);
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
		bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
		bootstrap.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(new ClientSendFileOutHandler());
			}
		});
		try {
			channelFuture = bootstrap.connect(ip, port);
			return channelFuture.sync().isSuccess();
		} catch (Exception e) {
			log.error("连接远程异常", e);
			workerGroup.shutdownGracefully();
			return false;
		}
	
	}
	
	public boolean connect(String ip, int port){
		Bootstrap bootstrap = new Bootstrap();
		workerGroup  = new NioEventLoopGroup();
		bootstrap.group(workerGroup);
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
		bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
		bootstrap.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(new EncodeOutHandler());
				ch.pipeline().addLast(new DecodeInHandler());
				ch.pipeline().addLast(new ClientRequestInHandler());
				ch.pipeline().addLast(new ClientClosedInHandler());
			}
		});
		try {
			channelFuture = bootstrap.connect(ip, port);
			return channelFuture.sync().isSuccess();
		} catch (Exception e) {
			log.error("连接远程异常", e);
			workerGroup.shutdownGracefully();
			return false;
		}
	}

	public void sendFile(GetAndSendFileRequest andSendFileRequest){
		channelFuture.channel().write(andSendFileRequest);
	}
	
	public void close(){
		workerGroup.shutdownGracefully();
	}
}